package com.itheima.interceptor;


import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){

        String uri = request.getRequestURI();
        log.info("uri = {}", uri);

        if (uri.contains("login")){
            return true;
        }

        String token = request.getHeader("token");

        if (token == null){
            log.info("token is null");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        try{
            Claims claims = JwtUtils.parserJwt(token);
            log.info("claims = {}", claims);
        } catch (Exception e){
            log.info("error : {}", e.getMessage());
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        }
        return true;
    }

}
